import { MineListType } from "@/types/mine"

export function createMine(list: MineListType[][], total: number) {
    const width = list[0].length, height = list.length
    do {
        const id = Math.floor(Math.random() * height * width)
        if (!list[Math.floor(id / width)][id % width].value) {
            list[Math.floor(id / width)][id % width].value = 1
            total--
        }
    } while (total)
    list.forEach((row, i) => {
        row.forEach((block, j) => {
            if (block.value) return
            let around = 0
            for (let x = -1; x <= 1; x++) {
                for (let y = -1; y <= 1; y++) {
                    if (x || y) {
                        const ix = i + x, iy = j + y
                        if (ix >= 0 && ix < height && iy >= 0 && iy < width && list[ix][iy].value) {
                            around++
                        }
                    }
                }
            }
            block.around = around
        })
    })
}

export function around(list: MineListType[][], row: number, col: number): number[] {
    const width = list[0].length, height = list.length, tmp = [] as number[]
    for (let x = -1; x <= 1; x++) {
        for (let y = -1; y <= 1; y++) {
            if (x || y) {
                const ix = col + x, iy = row + y
                if (ix >= 0 && ix < width && iy >= 0 && iy < height && !list[iy][ix].open && list[iy][ix].mark != 1) {
                    tmp.push(iy * width + ix)
                }
            }
        }
    }
    return tmp
}

export function aroundMark(list: MineListType[][], row: number, col: number): number {
    const width = list[0].length, height = list.length
    let num = 0
    for (let x = -1; x <= 1; x++) {
        for (let y = -1; y <= 1; y++) {
            if (x || y) {
                const ix = col + x, iy = row + y
                if (ix >= 0 && ix < width && iy >= 0 && iy < height && list[iy][ix].mark == 1) {
                    num++
                }
            }
        }
    }
    return num
}